<?php

class weixinController
{
   
	 
	public $data=array();
	private  $access_token=''; 
	public $follower=array();
	function __construct()
	{
		$this->getTextMsg();
		
		//$this->errorlog($this->event);
	}
	public function errorlog($content)
   {
    $fp = fopen("error.txt","w");
    fwrite($fp,$content);
    fclose($fp);
   }
   //用appid和secret获取token
   public function getToken($appid,$secret)
   {
   	$url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;
   	$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);

   	$token=json_decode($result);
   	
   	$this->access_token=$token->access_token;		
   	return $this->access_token;
   }
   //auth2.0获取用户信息
   public function getUserByCode($appid,$secret,$code)
   {
   	$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
   	$json = file_get_contents($url);
   	$arr = json_decode($json,true);
   	return $arr;
   }
   public function getUserInfo($openid,$access_token='')
   {
   	if($access_token=='')
   	{
   		$access_token=$this->access_token;
   	}
   $url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
   $json = file_get_contents($url);//获取微信用户基本信息
   $arr = json_decode($json,true);
   return $arr;
}
   //用post方法获取数据
   public function post_it($url,$data)
   {
   	  $curl = curl_init();
   	  curl_setopt($curl, CURLOPT_URL, $url);
   	  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
      curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
   	  curl_setopt($curl, CURLOPT_POST, 1);
   	  curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
   	  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
     	$result = curl_exec($curl);
   	   if (curl_errno($curl)) {
   		return 'Errno'.curl_error($curl);
   	    }
   	  curl_close($curl);
   	   return $result;
   }
   public function get_it($url)
   {
   	  $ch = curl_init();
   	  curl_setopt($ch, CURLOPT_URL,$url);
   	  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
   	  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
   	  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   	  $result = curl_exec($ch);
   	  return $result ;
   }
   public function getFollower($token='')
   {
   	$this->access_token=$token==''?$this->access_token:$token;
   	if($this->access_token!='')
   	  {
   	  	$url='https://api.weixin.qq.com/cgi-bin/user/get?access_token='.$this->access_token.'';
   	  	
        $result =$this->get_it($url);

   	  	$data=json_decode($result);
   	  	$data=(array)$data;
   	  	
   	  	$this->follower=$data[data];
   	  	$this->follower=$this->follower->openid;
   	  }
   	  return $this->follower;
   }
	public function valid($token)
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature($token)){
        	return $echoStr;
        	//exit;
        }
    }
    /*
     * {
    "touser":"OPENID",
    "msgtype":"news",
    "news":{
        "articles": [
         {
             "title":"Happy Day",
             "description":"Is Really A Happy Day",
             "url":"URL",
             "picurl":"PIC_URL"
         },
         {
             "title":"Happy Day",
             "description":"Is Really A Happy Day",
             "url":"URL",
             "picurl":"PIC_URL"
         }
         ]
    }
}
      
     * 
     * */
    public function sendImgMsg($openid,$arr,$token='')
    {
    	$this->access_token=$token==''?$this->access_token:$token;
    	$img_array=array('touser'=>$openid,
    			'msgtype'=>'news',
    			'news'=>''
    	);
    	foreach ($arr as $k=>$v)
    	{
    		$arr[$k]['pic_url']='http://'.$_SERVER['HTTP_HOST'].'/'.$v['thumb'];
    	}
    	$img_array['news']['articles']=$arr;
    	$data=urldecode(json_encode($img_array));
  //print_r($data);
    	
    	if($this->access_token!='')
    	{
    		$url="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$this->access_token;
    		$this->post_it($url, $data);
    
    	}
    }
    public function create_menu($data,$token='')
    {
    	$result='';
    	$this->access_token=$token==''?$this->access_token:$token;
    	if($this->access_token!='')
    	{
    		$url='https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$this->access_token;
    	   $result=$this->post_it($url,$data);
    		
    	}
    	return $result;
    }
    public function get_menu($token)
    {
    	$result='';
    	$this->access_token=$token==''?$this->access_token:$token;
    	if($this->access_token!='')
    	{
    	   $url="https://api.weixin.qq.com/cgi-bin/menu/get?access_token=".$this->access_token;
    	   $result=$this->get_it($url);
    	}
    	return $result;
    }
    public function del_menu($token='')
    {
    	
    	$result='';
    	$this->access_token=$token==''?$this->access_token:$token;
    	if($this->access_token!='')
    	{
    		$url="https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=".$this->access_token;
    		$result=$this->get_it($url);
    	}
    	return $result;
    }
    public function send_to_all($data,$type,$token='')
    {
    	$this->access_token=$token==''?$this->access_token:$token;
    	if($this->access_token!='')
    	{
    		$follower=$this->getFollower();
    		
    	  if($type=='text')
    	  {
    	  	if(count($follower)>0)
    	  	{
    	  	    foreach($follower as $k=>$v)
    	  	   {
    	  	   	  
    	  	   	 $this->sendTextMsg($v,$data);
    	  	   }
    	  	}	
    	  }
    	  else if($type=='image')
    	  {
    	  	if(count($follower)>0)
    	  	{
    	  		foreach($follower as $k=>$v)
    	  		{
    	  			
    	  			$this->sendImgMsg($v,$data);
    	  		}
    	  	}
    	  }
    	}
    }
    public function sendTextMsg($openid,$text,$token)
    {
    	$data='{
    "touser":"'.$openid.'",
    "msgtype":"text",
    "text":
    {
        "content":"'.$text.'"
    }
}';
    	
    	$this->access_token=$token==''?$this->access_token:$token;
    	if($this->access_token!='')
    	{
    		$url="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$this->access_token;
    		$this->post_it($url, $data);
    		
    	}
    }
    public function getTextMsg()
	{
		
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
		
		if (!empty($postStr))
		{    $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
		     //print_r($postObj);
			 
			$this->data=(array)$postObj; 
			
		}
		
		
	}
	public function replyTextMsg($contentStr,$toUser='')
	{
		$msgType = "text";
		$time = time();
		$ToUserName=$toUser==''?$this->data['FromUserName']:$toUser;
        $textTpl = "<xml>
			<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							</xml>";  
		
	
			 
             
             $resultStr = sprintf($textTpl, $ToUserName, $this->data['ToUserName'], $time, $msgType, $contentStr);
              echo $resultStr; 
		
	}
	/**/
	public function replyImgMsg($arr)
	{
		$msgType = "news";
		$ToUserName=$this->data['FromUserName'];
		$num=count($arr);
		$time = time();
		$item='';
       
		
		if($num>0)
		{
			foreach($arr as $k=>$v)
		  {
			$itemTpl="<item><Title><![CDATA[%s]]></Title> 
<Description><![CDATA[%s]]></Description>
<PicUrl><![CDATA[%s]]></PicUrl>
<Url><![CDATA[%s]]></Url>
</item>";
            $item.= sprintf($itemTpl, $v['title'], $v['description'], "http://".$_SERVER['HTTP_HOST']."/".$v['thumb'], $v['url']);
		   }
			$textTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<ArticleCount>%s</ArticleCount>
<Articles>

".$item."

</Articles>
</xml>";   
             
             $resultStr = sprintf($textTpl, $ToUserName, $this->data['ToUserName'], $time, $msgType, $num);
              echo $resultStr; 
		}
	}
	
    public function replyMusicMsg($url,$title)
	{
		
		$msgType = "music";
		$time = time();
        $textTpl = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[%s]]></MsgType>
<Music>
<Title><![CDATA[%s]]></Title>
<Description><![CDATA[%s]]></Description>
<MusicUrl><![CDATA[%s]]></MusicUrl>
<HQMusicUrl><![CDATA[%s]]></HQMusicUrl>

</Music></xml>";  
		
		
			$resultStr = sprintf($textTpl, $this->data['FromUserName'], $this->data['ToUserName'], $time, $msgType, $title,'希望你喜欢',$url,$url,'');
		
            echo $resultStr; 
		
	}
		
	private function checkSignature($token)
	{
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];	
        		
		
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
}